package com.zxh.blog.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import com.google.android.flexbox.FlexboxLayout
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.zxh.blog.R


class HistoryFragment : Fragment() {
    // 历史记录布局
    private lateinit var mSearchRecordsLayout: FlexboxLayout

    // 删除全部记录按钮
    private lateinit var mRemoveAllBtn: ImageButton

    // SharedPreferences对象
    private lateinit var mSharedPreferences: SharedPreferences

    // 历史记录表
    private val mSearchRecordsList = mutableListOf<String>()

    private var mListener: OnSearchHistoryClickListener? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_history, container, false)

        // 初始化控件
        mSearchRecordsLayout = view.findViewById(R.id.search_records)
        mRemoveAllBtn = view.findViewById(R.id.btn_del_all)
        mSharedPreferences = requireContext().getSharedPreferences("search_history", Context.MODE_PRIVATE)

        // 读取本地历史数据
        restoreSearchHistory()

        // 加载搜索历史记录到布局中
        loadSearchHistory()
        return view
    }

    override fun onStart() {
        super.onStart()
        // 清除全部记录
        mRemoveAllBtn.setOnClickListener {
            showRemoveAllConfirmationDialog()
        }
    }

    /**
     *  在 onAttach 方法中，我们通过获取 context 对象来判断当前 Activity
     *  是否实现了 OnSearchHistoryClickListener 接口。
     *  如果实现了，我们就将 context 转换为 OnSearchHistoryClickListener 类型，
     *  并将结果赋值给 mListener，以便在后面的代码中使用。
     *  如果没有实现，我们就会抛出一个异常提示开发者必须实现这个接口。
     */
    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is OnSearchHistoryClickListener) {
            mListener = context
        } else {
            throw RuntimeException("$context 必须实现 OnSearchHistoryClickListener 接口")
        }
    }

    /**
     *  在 onDetach 方法中，
     *  我们将 mListener 置为 null，
     *  以避免 Fragment 和 Activity 的持有关系发生内存泄漏。
     */
    override fun onDetach() {
        super.onDetach()
        mListener = null
    }

    private fun showRemoveAllConfirmationDialog() {
        val dialogBuilder: AlertDialog.Builder = AlertDialog.Builder(requireContext())
        dialogBuilder.setMessage("确认删除全部记录吗？")
            .setCancelable(false)
            .setPositiveButton("确认") { _, _ ->
                // 清除记录
                clearAllSearchRecords()
                // 重新加载MineFragment
                requireActivity().supportFragmentManager.beginTransaction()
                    .replace(R.id.fragmentContainer, HistoryFragment())
                    .commit()
            }
            .setNegativeButton("取消") { dialog, _ ->
                dialog.cancel()
            }
        val alert: AlertDialog = dialogBuilder.create()
        alert.show()
    }

    /**
     * 动态添加搜索记录到 FlexboxLayout 中
     */
    @SuppressLint("ResourceAsColor")
    private fun loadSearchHistory() {
        mSearchRecordsLayout.removeAllViews()
        for (history in mSearchRecordsList) {
            // 整体布局样式
            val container = LinearLayout(requireContext())
            container.orientation = LinearLayout.HORIZONTAL
            container.setBackgroundResource(R.drawable.shape_history_bg)
            container.gravity = Gravity.CENTER_VERTICAL

            // 文本样式
            val textView = TextView(requireContext())
            textView.text = history
            textView.setTextColor(Color.BLACK)
            textView.gravity = Gravity.CENTER_VERTICAL
            textView.height = dpToPx(30)
            val layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            layoutParams.setMargins(dpToPx(10), 0, 0, 0) // 设置左边距为 10dp
            textView.layoutParams = layoutParams

            // 删除单个记录按钮样式
            val deleteButton = ImageButton(requireContext())
            deleteButton.setImageResource(R.drawable.delete)
            deleteButton.scaleType = ImageView.ScaleType.FIT_CENTER
            deleteButton.setBackgroundColor(Color.TRANSPARENT)
            val buttonLayoutParams = LinearLayout.LayoutParams(dpToPx(35), dpToPx(35))
            deleteButton.layoutParams = buttonLayoutParams

            container.addView(textView)
            container.addView(deleteButton)

            val lp = FlexboxLayout.LayoutParams(
                FlexboxLayout.LayoutParams.WRAP_CONTENT,
                FlexboxLayout.LayoutParams.WRAP_CONTENT
            )
            lp.setMargins(dpToPx(10), dpToPx(10), dpToPx(10), dpToPx(10))
            container.layoutParams = lp

            // 文本点击事件
            textView.setOnClickListener {
                mListener?.onSearchHistoryClick(textView.text.toString())
            }

            // 删除单个历史记录点击事件
            deleteButton.setOnClickListener {
                removeSearchRecord(history)
                mSearchRecordsLayout.removeView(container)
            }
            mSearchRecordsLayout.addView(container)
        }
    }

    /**
     *  dp转像素
     */
    private fun dpToPx(dp: Int): Int {
        val density = resources.displayMetrics.density
        return (dp * density).toInt()
    }


    /**
     *  删除单个历史记录
     */
    private fun removeSearchRecord(history: String) {
        mSearchRecordsList.remove(history)
        // 将搜索记录保存到 SharedPreferences 中
        mSharedPreferences.edit().putString("search_history", Gson().toJson(mSearchRecordsList)).apply()
        // 重新加载MineFragment
        requireActivity().supportFragmentManager.beginTransaction()
            .replace(R.id.fragmentContainer, HistoryFragment())
            .commit()
    }

    /**
     * 从本地恢复搜索记录（使用 List 存储记录）
     */
    private fun restoreSearchHistory() {
        val historyJson = mSharedPreferences.getString("search_history", null)
        if (historyJson != null) {
            mSearchRecordsList.addAll(Gson().fromJson(historyJson, object : TypeToken<List<String>>() {}.type))
        }
    }


    /**
     *  清除所有记录
     */
    private fun clearAllSearchRecords() {
        // 清空记录表
        mSearchRecordsList.clear()
        mSearchRecordsLayout.removeAllViewsInLayout()
        val editor = mSharedPreferences.edit()
        editor.clear()
        editor.apply()
        // 重新加载MineFragment
        requireActivity().supportFragmentManager.beginTransaction()
            .replace(R.id.fragmentContainer, HistoryFragment())
            .commit()
    }

    /**
     *  将历史记录文本赋给SearchActivity中的搜索框的监听接口
     */
    interface OnSearchHistoryClickListener {
        fun onSearchHistoryClick(text: String)
    }

}